{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Test Model\n",
    "\n",
    "In this notebook, we are testing our model performance on test Dataset.\n",
    "\n",
    "**1. Import Required Libraries:-** "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torchvision import transforms\n",
    "import torch\n",
    "import torch.optim as optim\n",
    "from torch.utils.data import random_split, DataLoader\n",
    "import time\n",
    "import cv2\n",
    "import numpy as np\n",
    "import os\n",
    "import matplotlib.pyplot as plt\n",
    "#Local Imports\n",
    "from transforms import Normalize,ToTensor\n",
    "from dataset import HeadposeDataset\n",
    "from model import FSANet\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2. Compose Augmentation Transform and Create Dataset:-**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x (images) shape:  (1969, 64, 64, 3)\n",
      "y (poses) shape:  (1969, 3)\n"
     ]
    }
   ],
   "source": [
    "transform = transforms.Compose([\n",
    "            Normalize(mean=127.5,std=128),\n",
    "            ToTensor()\n",
    "            ])\n",
    "\n",
    "data_path = '../data/type1/test'\n",
    "\n",
    "hdb = HeadposeDataset(data_path,transform=transform)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**3. Create Dataloader to batch over test dataset:-**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Setup dataloaders for train and validation\n",
    "batch_size = 64\n",
    "\n",
    "test_loader = DataLoader(hdb, \n",
    "                          batch_size=batch_size,\n",
    "                          shuffle=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**4. Define Model Function:-**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = FSANet(var=False)\n",
    "#Load Model Checkpoint\n",
    "chkpt_dic = torch.load('../checkpoints/fsa1x1-08082020.chkpt')\n",
    "model.load_state_dict(chkpt_dic['best_states']['model'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**5. Place Model in GPU:-**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FSANet(\n",
       "  (msms): MultiStreamMultiStage(\n",
       "    (avgpool): AvgPool2d(kernel_size=2, stride=2, padding=0)\n",
       "    (s0_conv0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=3)\n",
       "        (pointwise): Conv2d(3, 16, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv1_0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=16)\n",
       "        (pointwise): Conv2d(16, 32, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv1_1): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32)\n",
       "        (pointwise): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv1_out): Conv2dAct(\n",
       "      (conv): Conv2d(32, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv2_0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32)\n",
       "        (pointwise): Conv2d(32, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv2_1): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=64)\n",
       "        (pointwise): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv2_out): Conv2dAct(\n",
       "      (conv): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv3_0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=64)\n",
       "        (pointwise): Conv2d(64, 128, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv3_1): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=128)\n",
       "        (pointwise): Conv2d(128, 128, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s0_conv3_out): Conv2dAct(\n",
       "      (conv): Conv2d(128, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (maxpool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n",
       "    (s1_conv0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=3)\n",
       "        (pointwise): Conv2d(3, 16, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): ReLU()\n",
       "    )\n",
       "    (s1_conv1_0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=16)\n",
       "        (pointwise): Conv2d(16, 32, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv1_1): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32)\n",
       "        (pointwise): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv1_out): Conv2dAct(\n",
       "      (conv): Conv2d(32, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv2_0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=32)\n",
       "        (pointwise): Conv2d(32, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv2_1): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=64)\n",
       "        (pointwise): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv2_out): Conv2dAct(\n",
       "      (conv): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv3_0): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=64)\n",
       "        (pointwise): Conv2d(64, 128, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv3_1): SepConvBlock(\n",
       "      (conv): SepConv2d(\n",
       "        (depthwise): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), groups=128)\n",
       "        (pointwise): Conv2d(128, 128, kernel_size=(1, 1), stride=(1, 1))\n",
       "      )\n",
       "      (bn): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (act): Tanh()\n",
       "    )\n",
       "    (s1_conv3_out): Conv2dAct(\n",
       "      (conv): Conv2d(128, 64, kernel_size=(1, 1), stride=(1, 1))\n",
       "      (act): Tanh()\n",
       "    )\n",
       "  )\n",
       "  (fgsm): FineGrainedStructureMapping(\n",
       "    (attention_maps): ScoringFunction(\n",
       "      (reduce_channel): Conv2dAct(\n",
       "        (conv): Conv2d(64, 1, kernel_size=(1, 1), stride=(1, 1))\n",
       "        (act): Sigmoid()\n",
       "      )\n",
       "    )\n",
       "    (fm): Linear(in_features=64, out_features=960, bias=True)\n",
       "    (fc): Linear(in_features=192, out_features=35, bias=True)\n",
       "  )\n",
       "  (caps_layer): CapsuleLayer1d()\n",
       "  (eaf): ExtractAggregatedFeatures()\n",
       "  (esp_s1): ExtractSSRParams(\n",
       "    (shift_fc): Linear(in_features=4, out_features=3, bias=True)\n",
       "    (scale_fc): Linear(in_features=4, out_features=3, bias=True)\n",
       "    (pred_fc): Linear(in_features=8, out_features=9, bias=True)\n",
       "  )\n",
       "  (esp_s2): ExtractSSRParams(\n",
       "    (shift_fc): Linear(in_features=4, out_features=3, bias=True)\n",
       "    (scale_fc): Linear(in_features=4, out_features=3, bias=True)\n",
       "    (pred_fc): Linear(in_features=8, out_features=9, bias=True)\n",
       "  )\n",
       "  (esp_s3): ExtractSSRParams(\n",
       "    (shift_fc): Linear(in_features=4, out_features=3, bias=True)\n",
       "    (scale_fc): Linear(in_features=4, out_features=3, bias=True)\n",
       "    (pred_fc): Linear(in_features=8, out_features=9, bias=True)\n",
       "  )\n",
       "  (ssr): SSRLayer()\n",
       ")"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Place all the necessary things in GPU \n",
    "device = torch.device(\"cuda\")\n",
    "model.to(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**6. Define Testing Function:-**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test_net():\n",
    "    yaw_loss = []\n",
    "    pitch_loss = []\n",
    "    roll_loss = []\n",
    "    model.eval()\n",
    "    with torch.no_grad():\n",
    "        for batch_i, data in enumerate(test_loader):\n",
    "            # get the input images and their corresponding poses\n",
    "            images,gt_poses = data\n",
    "\n",
    "            # put data inside gpu\n",
    "            images = images.float().to(device)\n",
    "            gt_poses = gt_poses.float().to(device)\n",
    "\n",
    "            # call model forward pass\n",
    "            predicted_poses = model(images)\n",
    "\n",
    "            abs_loss = torch.abs(gt_poses-predicted_poses)\n",
    "            \n",
    "            abs_loss = abs_loss.cpu().numpy().mean(axis=0)\n",
    "            \n",
    "            yaw_loss.append(abs_loss[0])\n",
    "            pitch_loss.append(abs_loss[1])\n",
    "            roll_loss.append(abs_loss[2])\n",
    "    \n",
    "    yaw_loss = np.mean(yaw_loss)\n",
    "    pitch_loss = np.mean(pitch_loss)   \n",
    "    roll_loss = np.mean(roll_loss)\n",
    "    print('Mean Absolute Error:-')\n",
    "    print(f'Yaw: {yaw_loss:.2f}, Pitch: {pitch_loss:.2f}, Roll: {roll_loss:.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**7. Test Model and print Mean Absolute Error:-**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Mean Absolute Error:-\n",
      "Yaw: 4.85, Pitch: 6.27, Roll: 4.96\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    # test your network\n",
    "    test_net()\n",
    "except KeyboardInterrupt:\n",
    "    print('Stopping Testing...')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
